//
//  FirstViewController.swift
//  AutoPrint
//
//  Created by 胡玉葱 on 16/9/25.
//  Copyright © 2016年 fatcat. All rights reserved.
//

import UIKit

class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate, AlbumBackCleanCachesDelegate {

    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }
    
    let CACHES_PATH = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
    let LOGIN_LOST_ALERT_ID = 101
    
    var tableView:UITableView!
    var listItems:NSMutableArray!
//    var newAddItems:NSArray!
    
    var refreshControl:UDRefreshControl! // 上方 下拉刷新
    var refreshSpinnerAtSectionHeader:UIActivityIndicatorView! // 云端文件 菊花加载
    
    var loginPleaseBtn: UIButton! // 请先登录 按钮
    var logined = false // 是否登陆
    
    var refreshPageControl: UDRefreshControl! // 下方 上拉加载更多
    var currentPage = 0 // 当前页 读取完数据就变1
    var pageLoadable = false // 是否可以加载更多
    
    var editButton: UIBarButtonItem! // 多选按钮
    var multiConfirmBtn: UIBarButtonItem! // 确认上传按钮
    var searchBtn: UIBarButtonItem! // 搜索按钮
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        print(CACHES_PATH)
        // 设置delegate中的VC
        let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appdelegate.firstVC = self
        // 首次启动时没有成功打开文件，现在补刀
        if appdelegate.urlToOpen != nil {
            openFile(appdelegate.urlToOpen!)
        }
        // 设置导航栏颜色
        navigationController?.navigationBar.barStyle = .Black
        navigationController?.navigationBar.barTintColor = Fatcat.THEME_COLOR
        navigationItem.titleView?.tintColor = UIColor.whiteColor()
        tabBarController?.tabBar.tintColor = Fatcat.THEME_COLOR
        
        // 下一个视图的返回键将显示 返回
        let backItem = UIBarButtonItem()
        backItem.title = "返回"
        navigationItem.backBarButtonItem = backItem
        
        // 多选切换按钮
        editButton = UIBarButtonItem(title: "多选", style: .Plain, target: self, action: #selector(FirstViewController.multiSelect(_:)))
        navigationItem.rightBarButtonItem = editButton
        
        // 上传按钮
        multiConfirmBtn = UIBarButtonItem(title: "上传", style: .Plain, target: self, action: #selector(FirstViewController.multiSubmit))
        
        searchBtn = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: #selector(FirstViewController.gotoSearch))
        navigationItem.leftBarButtonItem = searchBtn
        
        // 未登录时显示的请登录按钮，缺图标
        loginPleaseBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        loginPleaseBtn.center = CGPoint(x: view.center.x, y: view.center.y - 64)
        loginPleaseBtn.backgroundColor = UIColor.lightGrayColor()
        loginPleaseBtn.setTitle("请先登录", forState: .Normal)
        loginPleaseBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        loginPleaseBtn.layer.cornerRadius = 50
        loginPleaseBtn.addTarget(self, action: #selector(FirstViewController.gotoLogin), forControlEvents: .TouchUpInside)
        
        // 云端文件section顶部的旋转菊花
        refreshSpinnerAtSectionHeader = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
        refreshSpinnerAtSectionHeader.hidesWhenStopped = true
        
        // 上拉加载更多提示器
        refreshPageControl = UDRefreshControl(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        refreshPageControl.alpha = 0
        
        // 数组准备
        listItems = NSMutableArray()
        
        // tableview构造
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height), style: .Grouped)
        view.addSubview(tableView)
        tableView.tintColor = Fatcat.SELECTED_COLOR
        
        // 下拉刷新提示器
        refreshControl = UDRefreshControl(frame: CGRect(x: 0, y: -64, width: view.bounds.width, height: 64))
        tableView.addSubview(refreshControl)
        
        
        
        // MARK: 读取保存到cookies
        if NSUserDefaults.standardUserDefaults().objectForKey("user") != nil && NSUserDefaults.standardUserDefaults().objectForKey("cookies") != nil{
            logined = true
            loginPleaseBtn.alpha = 0 // 请登录按钮隐藏
            let cookiesData = NSUserDefaults.standardUserDefaults().objectForKey("cookies") as! NSData
            let cookies = NSKeyedUnarchiver.unarchiveObjectWithData(cookiesData) as! NSArray
            for cookie in cookies {
                NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie as! NSHTTPCookie)
            }
            
            self.refreshPageControl.alpha = 1
            
            if NSFileManager.defaultManager().fileExistsAtPath("\(CACHES_PATH)/ListItems.plist"){
                listItems = NSMutableArray(contentsOfFile: "\(CACHES_PATH)/ListItems.plist")
                currentPage = 1
                if listItems.count >= 10 { // 10条分一页
                    self.refreshPageControl.normalTitle = "下拉载入更多"
                    self.pageLoadable = true
                }else{
                    self.refreshPageControl.normalTitle = "没有更多了"
                    self.refreshPageControl.readyTitle = "没有更多了"
                    self.pageLoadable = false
                }
            }
            if NSUserDefaults.standardUserDefaults().objectForKey("lastRefresh") != nil{
                let timeStr = NSUserDefaults.standardUserDefaults().objectForKey("lastRefresh") as! String
                if UDDate.isTimeToRefresh(timeStr) {
                    refreshList(true)
                }else{
                    refreshList(false)
                }
            }else{
                refreshList(true)
            }
            
            
            // MARK: 不必每次打开都刷新，检查上次刷新时间，如果隔太久则刷新
            
            
        }
        
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.addSubview(loginPleaseBtn)
        
        
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 登陆完，再回到这个页面时，调用下列代码
        // TODO: 可能清理完缓存也要自动刷新一下
        if NSUserDefaults.standardUserDefaults().objectForKey("user") != nil && NSUserDefaults.standardUserDefaults().objectForKey("cookies") != nil{
            if !logined{
                logined = true
                loginPleaseBtn.alpha = 0
                let cookiesData = NSUserDefaults.standardUserDefaults().objectForKey("cookies") as! NSData
                let cookies = NSKeyedUnarchiver.unarchiveObjectWithData(cookiesData) as! NSArray
                for cookie in cookies {
                    NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie as! NSHTTPCookie)
                }
                
                self.refreshControl.alpha = 1
                self.refreshPageControl.alpha = 1
                
                if NSFileManager.defaultManager().fileExistsAtPath("\(CACHES_PATH)/ListItems.plist"){
                    listItems = NSMutableArray(contentsOfFile: "\(CACHES_PATH)/ListItems.plist")
                    tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic)
                    
                    currentPage = 1
                    if listItems.count >= 10 {
                        self.refreshPageControl.normalTitle = "下拉载入更多"
                        self.refreshPageControl.readyTitle = "松开刷新"
                        self.pageLoadable = true
                    }else{
                        self.refreshPageControl.normalTitle = "没有更多了"
                        self.refreshPageControl.readyTitle = "没有更多了"
                        self.pageLoadable = false
                    }
                }
                
                refreshList(true)
            }
        }else{
            flushLogin()
        }
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 下拉刷新准备刷新
        if tableView.contentOffset.y < -108 {
            
            if refreshControl.state == .Normal{
                refreshControl.readyToRefresh()
            }
            
        }else{
            // 松手刷新慢慢挪回去，取消刷新
            if refreshControl.state == .Ready{
                refreshControl.endRefresh()
            }
            
        }
        
        // 上拉，同理
        if pageLoadable {
            if tableView.contentOffset.y > tableView.contentSize.height - tableView.frame.height + 64{
                if refreshPageControl.state == .Normal{
                    refreshPageControl.readyToRefresh()
                }
                
            }else{
                if refreshPageControl.state == .Ready{
                    refreshPageControl.endRefresh()
                }
            }
        }
    }
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        // MARK: 下拉刷新出发
        if refreshControl.state == .Ready{
            if logined{
                refreshControl.beginRefresh()
                refreshList(true)
            }
            
        }
        if refreshPageControl.state == .Ready{
            
            if pageLoadable {
                print("load more")
                refreshPageControl.beginRefresh()
                loadMore()
            }
            
        }
    }
    func refreshList(update: Bool){
        //  这里update=false的话，因为真的不知道cookie会不会丢登陆。上面判断超过三天就不刷新的话，本地的登陆信息还在，以为已经登陆了
        if update{
            refreshSpinnerAtSectionHeader.startAnimating()
            refreshControl.beginRefresh()
        }
        
        
        // getList
        let getList = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        getList.HTTPMethod = "POST"
        
        
        let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!
        let cookiesHeader = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)
        getList.setValue(cookiesHeader["Cookie"], forHTTPHeaderField: "Cookie")
        
        // TODO: 分页形式 not tested
        getList.HTTPBody = NSString(string: "act=getList&page=1").dataUsingEncoding(NSUTF8StringEncoding)
        NSURLConnection.sendAsynchronousRequest(getList, queue: NSOperationQueue()) { (resp:NSURLResponse?, reData:NSData?, err:NSError?) in
            dispatch_async(dispatch_get_main_queue(), {
                self.refreshControl.endRefresh()
                self.refreshSpinnerAtSectionHeader.stopAnimating()
            })
            if err == nil{
                if let data = reData{
                    print(NSString(data: data, encoding: NSUTF8StringEncoding))
                    
                    // MARK: print cookie
                    //                    for cookie in NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!{
                    //                        print(cookie)
                    //                    }
                    
                    let jsonData = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! NSDictionary
                    //if jsonObj != nil {
                    //let jsonData = jsonObj as? NSDictionary
                    
                    if jsonData != nil{
                        //print(NSString(data: data, encoding: NSUTF8StringEncoding))
                        let reCode = jsonData?.objectForKey("code") as! Int
                        if reCode == 200 {
                            
                            if update{
                                let getList = jsonData?.objectForKey("data") as? NSArray
                                if getList != nil{
                                    self.listItems = NSMutableArray(array: getList!)
                                    self.currentPage = 1
                                }else{
                                    self.listItems = NSMutableArray()
                                }
                                
                                dispatch_async(dispatch_get_main_queue(), {
                                    self.tableView.reloadData()
                                    self.refreshPageControl.alpha = 1
                                    if self.listItems.count >= 10 {
                                        self.refreshPageControl.normalTitle = "下拉载入更多"
                                        self.refreshPageControl.readyTitle = "松开刷新"
                                        self.pageLoadable = true
                                    }else{
                                        self.refreshPageControl.normalTitle = "没有更多了"
                                        self.refreshPageControl.readyTitle = "没有更多了"
                                        self.pageLoadable = false
                                    }
                                    
                                })
                                
                                // MARK: 写入本地数据库 文件写在caches
                                self.listItems.writeToFile("\(self.CACHES_PATH)/ListItems.plist", atomically: true)
                                
                                // MARK: 记录刷新时间
                                let formatter = NSDateFormatter()
                                formatter.dateFormat = "yyyy-MM-dd"
                                NSUserDefaults.standardUserDefaults().setObject(formatter.stringFromDate(NSDate()), forKey: "lastRefresh")
                            }
                            
                            
                        }else if reCode == 201{
                            
                            let msg = jsonData?.objectForKey("message") as? String
                            if msg == "用户未登录" {
                                // MARK: 用户未登录
                                dispatch_async(dispatch_get_main_queue(), {
                                    self.flushLogin()
                                })
                            }
                            
                        }else{
                            dispatch_async(dispatch_get_main_queue(), {
                                UIAlertView(title: "出错:\(reCode)", message: jsonData?.objectForKey("message") as? String, delegate: nil, cancelButtonTitle: "OK").show()
                            })
                            
                        }
                        
                    }else{
                        print("json Error")
                    }
                    
                    //}
                    
                }
                
                
            }else{
                dispatch_async(dispatch_get_main_queue(), {
                    UIAlertView(title: "网络连接失败", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
                })
            }
        }
    }
    func loadMore(){
        refreshSpinnerAtSectionHeader.startAnimating()
        
        // getList
        let getList = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        getList.HTTPMethod = "POST"
        
        
        let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!
        let cookiesHeader = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)
        getList.setValue(cookiesHeader["Cookie"], forHTTPHeaderField: "Cookie")
        
        // TODO: 分页形式 not tested
        getList.HTTPBody = NSString(string: "act=getList&page=\(currentPage + 1)").dataUsingEncoding(NSUTF8StringEncoding)
        NSURLConnection.sendAsynchronousRequest(getList, queue: NSOperationQueue()) { (resp:NSURLResponse?, reData:NSData?, err:NSError?) in
            dispatch_async(dispatch_get_main_queue(), {
                self.refreshControl.endRefresh()
                self.refreshSpinnerAtSectionHeader.stopAnimating()
            })
            if err == nil{
                if let data = reData{
                    //print(NSString(data: data, encoding: NSUTF8StringEncoding))
                    
                    let jsonData = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! NSDictionary
                    //if jsonObj != nil {
                        //let jsonData = jsonObj as? NSDictionary
                        
                        if jsonData != nil{
                            let reCode = jsonData?.objectForKey("code") as! Int
                            if reCode == 200 {
                                let getList = jsonData?.objectForKey("data") as? NSArray
                                if getList != nil{
                                    self.listItems.addObjectsFromArray(getList as! [AnyObject])
                                    dispatch_async(dispatch_get_main_queue(), {
                                        self.tableView.reloadData()
                                        self.refreshPageControl.alpha = 1
                                        if getList!.count >= 10 {
                                            self.refreshPageControl.normalTitle = "下拉载入更多"
                                            self.refreshPageControl.readyTitle = "松开刷新"
                                            self.pageLoadable = true
                                        }else{
                                            self.refreshPageControl.normalTitle = "没有更多了"
                                            self.refreshPageControl.readyTitle = "没有更多了"
                                            self.pageLoadable = false
                                        }
                                        
                                    })
                                    self.currentPage += 1
                                }
                                
                                // MARK: 记录刷新时间
//                                let formatter = NSDateFormatter()
//                                formatter.dateFormat = "yyyy-MM-dd"
//                                NSUserDefaults.standardUserDefaults().setObject(formatter.stringFromDate(NSDate()), forKey: "lastRefresh")
                                
                            }else if reCode == 201{
                                dispatch_async(dispatch_get_main_queue(), {
                                    self.flushLogin()
                                })
                            }else{
                                dispatch_async(dispatch_get_main_queue(), {
                                    UIAlertView(title: "出错:\(reCode)", message: jsonData?.objectForKey("message") as? String, delegate: nil, cancelButtonTitle: "OK").show()
                                })
                                
                            }
                            
                        }else{
                            print("json Error")
                        }
                        
                    //}
                    
                }
                
                
            }else{
                dispatch_async(dispatch_get_main_queue(), {
                    UIAlertView(title: "网络连接失败", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
                })
            }
        }
    }

    
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 2
        case 1:
            return listItems.count
        default:
            return 1
        }
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 1{
            return 64
        }
        return 44
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "item")
        
        if indexPath.section == 0 {
            let icon = UIImageView(frame: CGRect(x: 24, y: 8, width: 28, height: 28))
            cell.addSubview(icon)
            
            let nameLabel = UILabel(frame: CGRect(x: 72, y: 8, width: view.bounds.width - 80, height: 28))
            cell.addSubview(nameLabel)
            
            cell.accessoryType = .DisclosureIndicator
            
            if indexPath.row == 0 {
                icon.image = UIImage(named: "documents_icon_folder")
                nameLabel.text = "本地文件"
            }else if indexPath.row == 1{
                icon.image = UIImage(named: "photo")
                nameLabel.text = "手机相册"
            }
        }else if indexPath.section == 1{
            // MARK: 列表显示数据
            
            var indent: CGFloat = 0.0
            if tableView.editing {
                indent = 36
            }
            let thisFileItem = listItems.objectAtIndex(indexPath.row) as! NSDictionary
            let icon = UIImageView(frame: CGRect(x: indent + 16, y: 8, width: 48, height: 48))
            icon.contentMode = .Center
            icon.backgroundColor = UIColor.lightGrayColor()
            cell.addSubview(icon)
            
            let nameLabel = UILabel(frame: CGRect(x: indent + 72, y: 8, width: view.bounds.width - 80, height: 20))
            
            cell.addSubview(nameLabel)
            
            let subLabel = UILabel(frame: CGRect(x: indent + 72, y: 36, width: view.bounds.width - 80, height: 20))
            
            subLabel.textColor = UIColor.lightGrayColor()
            cell.addSubview(subLabel)
            
            let fileName = thisFileItem.objectForKey("sourceFileName") as? String
            nameLabel.text = fileName
            subLabel.text = UDDate.shortDate(thisFileItem.objectForKey("addTime") as! String)
            
            // MARK: 文件图标
            if fileName != nil {
                let fileType = fileName!.componentsSeparatedByString(".").last
                if fileType != nil {
                    if fileType == "doc" || fileType == "docx" {
                        icon.backgroundColor = UIColor.clearColor()
                        icon.image = UIImage(named: "documents_icon_doc")
                    }else if fileType == "xls" || fileType == "xlsx" {
                        icon.backgroundColor = UIColor.clearColor()
                        icon.image = UIImage(named: "documents_icon_xls")
                    }else if fileType == "ppt" || fileType == "pptx" {
                        icon.backgroundColor = UIColor.clearColor()
                        icon.image = UIImage(named: "documents_icon_ppt")
                    }else if fileType == "pdf"{
                        icon.backgroundColor = UIColor.clearColor()
                        icon.image = UIImage(named: "documents_icon_pdf")
                    }else if fileType == "txt"{
                        icon.backgroundColor = UIColor.clearColor()
                        icon.image = UIImage(named: "documents_icon_txt")
                    }else if fileType == "png" || fileType == "jpg" || fileType == "jpeg" || fileType == "bmp" {
                        icon.backgroundColor = UIColor.clearColor()
                        icon.image = UIImage(named: "photo")
                    }
                }
            }
        }
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        if !tableView.editing {
            tableView.deselectRowAtIndexPath(indexPath, animated: true)
            hidesBottomBarWhenPushed = true
            if indexPath.section == 0{
                // 去本地文件管理器
                if indexPath.row == 0{
                    navigationController?.pushViewController(FileViewController(), animated: true)
                }else if indexPath.row == 1{
                    // 打开手机相册
                    if NSUserDefaults.standardUserDefaults().objectForKey("user") == nil {
                        
                        presentViewController(UDLoginViewController(), animated: true, completion: nil)
                    }else{
                        let album = AlbumViewController()
                        album.delegate = self
                        navigationController?.pushViewController(album, animated: true)
                    }
                    
                }
                
                
            }else if indexPath.section == 1 {
                // 进入文件详情
                let thisRowItem = listItems.objectAtIndex(indexPath.row) as! NSDictionary
                let filePath = thisRowItem.objectForKey("filePath") as! String
                let fileName = thisRowItem.objectForKey("sourceFileName") as! String
                let fileMD5 = thisRowItem.objectForKey("fileMd5") as! String
                navigationController?.pushViewController(FileOLPreViewController(name: fileName, path: filePath, md5: fileMD5), animated: true)
            }
        }else{
            
        }
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1{
            let myFileHeader = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 0))
            let textLabel = UILabel(frame: CGRect(x: 16, y: 0, width: 64, height: 8))
            textLabel.textColor = UIColor.grayColor()
            textLabel.font = UIFont.systemFontOfSize(14)
            textLabel.text = "云端文件"
            myFileHeader.addSubview(textLabel)
            // 菊花加载器在这添加
            refreshSpinnerAtSectionHeader.frame = CGRect(x: 88, y: 0, width: 0, height: 0)
            myFileHeader.addSubview(refreshSpinnerAtSectionHeader)
            
            return myFileHeader
        }else{
            return UIView(frame: CGRect.zero)
        }
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 1{
            return 64
        }
        return 0
    }
    
    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 1{
            let footer = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
            footer.addSubview(refreshPageControl)
            return footer
        }
        return nil
    }
    
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if alertView.tag == LOGIN_LOST_ALERT_ID{
            if buttonIndex == 1{
                presentViewController(UDLoginViewController(), animated: true, completion: nil)
            }
        }
    }
    
    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        if indexPath.section == 1{
            return true
        }
        return false
    }
    
    func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
        return UITableViewCellEditingStyle.init(rawValue: UITableViewCellEditingStyle.Delete.rawValue | UITableViewCellEditingStyle.Insert.rawValue)!
    }
    
    
    
    func multiSelect(sender: UIBarButtonItem){
        // MARK:多选按钮点击
        
        
        if tableView.editing {
            sender.title = "多选"
            navigationItem.leftBarButtonItem = searchBtn
            navigationItem.rightBarButtonItem = sender
        }else{
            sender.title = "取消"
            navigationItem.leftBarButtonItem = sender
            navigationItem.rightBarButtonItem = multiConfirmBtn
        }
        tableView.setEditing(!tableView.editing, animated: true)
        tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .None)
        
        
    }
    
    func multiSubmit(){
        //MARK: 在线文件多选直接上传
        if tableView.indexPathsForSelectedRows != nil{
            
            if NSUserDefaults.standardUserDefaults().objectForKey("user") == nil {
                presentViewController(UDLoginViewController(), animated: true, completion: nil)
                
            }else{
                var filesToUpload: [UDFile] = []
                for index in tableView.indexPathsForSelectedRows! {
                    let file = listItems.objectAtIndex(index.row) as! NSDictionary
                    let fileName = file.objectForKey("sourceFileName") as? String
                    let fileMD5 = file.objectForKey("fileMd5") as? String
                    let filePath = file.objectForKey("filePath") as? String
                    filesToUpload.append(UDFile(filePath: filePath, fileName: fileName, fileSize: "在线文件", fileMD5: fileMD5))
                }
                hidesBottomBarWhenPushed = true
                navigationController?.pushViewController(FileReadyViewController(files: filesToUpload, step0VC: self), animated: true)
            }
            multiSelect(editButton)
        }else{
            UIAlertView(title: "请选择文件", message: nil, delegate: nil, cancelButtonTitle: "OK").show()
        }
        
    }
    
    func openFile(url: NSURL){
        //MARK: 其他应用打开时调用
        let appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appdelegate.urlToOpen = nil
        
        tabBarController?.selectedIndex = 0
        
        // bug 从其他地方进入preview tabbar会消失
        let showView = navigationController?.visibleViewController?.isEqual(self)
        if showView != nil {
            if showView! {
                hidesBottomBarWhenPushed = true
            }
        }
        
        navigationController?.pushViewController(FilePreViewController(url: url), animated: true)
        //presentViewController(FilePreViewController(url: url), animated: true, completion: nil)
    }
    
    func gotoLogin(){
        presentViewController(UDLoginViewController(), animated: true, completion: nil)
    }
    func gotoSearch(){
        hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(SearchOLViewController(), animated: false)
    }
    
    func flushLogin(){
        self.logined = false
        self.listItems = NSMutableArray()
        self.listItems.writeToFile("\(self.CACHES_PATH)/ListItems.plist", atomically: true)
        self.currentPage = 0
        self.pageLoadable = false
        self.tableView.reloadData()
        // MARK:请先登录"
        self.refreshPageControl.alpha = 0
        self.loginPleaseBtn.alpha = 1
        self.refreshControl.alpha = 0
        if NSUserDefaults.standardUserDefaults().objectForKey("user") != nil{
            let alertLoginLost = UIAlertView(title: "登录已过期", message: nil, delegate: self, cancelButtonTitle: "忽略")
            alertLoginLost.tag = self.LOGIN_LOST_ALERT_ID
            alertLoginLost.addButtonWithTitle("重新登录")
            alertLoginLost.show()
            NSUserDefaults.standardUserDefaults().removeObjectForKey("user")
        }
        if NSUserDefaults.standardUserDefaults().objectForKey("lastRefresh") != nil{
            NSUserDefaults.standardUserDefaults().removeObjectForKey("lastRefresh")
        }
    }
    
    func navigationBackFrom(albumViewController: AlbumViewController) {
        
        
        let b = navigationController?.visibleViewController?.isEqual(self)
        if b != nil {
            if b! {
                print("album back clear caches")
                let ls = try? NSFileManager.defaultManager().contentsOfDirectoryAtPath("\(CACHES_PATH)/photo")
                if ls != nil {
                    print(ls!)
                    for item in ls!{
                        _ = try? NSFileManager.defaultManager().removeItemAtPath("\(CACHES_PATH)/photo/\(item)")
                    }
                }
            }
        }
        
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        hidesBottomBarWhenPushed = false
    }

}
